package servlet.song;

import pojo.Songs;
import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/song/getSongList")
public class SongListServlet extends HttpServlet {
    private SongsService songService = new SongsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer startIndex = Integer.valueOf(request.getParameter("startIndex"));
        Integer targetTotal = Integer.valueOf(request.getParameter("targetTotal"));
        Integer pageSize = targetTotal;  // 每页显示的条目数

        // 获取歌曲列表
        List<Songs> songList = songService.selectSongList(startIndex, targetTotal);

        // 获取总歌曲数
        Integer totalCount = songService.getTotalSongCount();  // 返回数据库中的歌曲总数
        Integer totalPages = (int) Math.ceil(totalCount / (double) pageSize);

        // 将歌曲列表、总页数和当前页码等信息存储在请求域中
        request.getSession().setAttribute("songList", songList);
        request.getSession().setAttribute("totalCount", totalCount);
        request.getSession().setAttribute("totalPages", totalPages);
        request.getSession().setAttribute("targetTotal", targetTotal);
        request.getSession().setAttribute("currentPage", (startIndex / targetTotal) + 1);  // 当前页码，假设startIndex从0开始

        // 转发请求到 songList.jsp
        RequestDispatcher dispatcher = request.getRequestDispatcher("/play/songlists.jsp");
        dispatcher.forward(request, response);
    }
}
